package com.jixiantubu.luntan;

import java.io.File;
import java.util.List;

import com.example.jixiantubu.R;
import com.jixiantubu.index.MainActivity;
import com.jixiantubu.util.Config;
import com.jixiantubu.util.MyApplication;
import com.jixiantubu.util.StringUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;

public class FatieActivity extends Activity implements OnClickListener {
	EditText editText1, editText2;
	TextView textView1, textView2, textView3;
	ImageView imageView1, imageView2;
	LinearLayout linearLayout;
	int index = -1;// 记录要替换的图片 当为-1时 为新增
	List<String> imgs_path=null;// 上传图片的路径
	String tempImgName;// 图片姓名
	String title, content;
	Dialog dialog;
	int num = 400;
	private CharSequence temp;
	private int selectionStart;
	private int selectionEnd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_fatie);
		initViews();
		initData();
	}

	private void initViews() {
		editText1 = (EditText)findViewById(R.id.tiezi_fabiao_title);
		editText2 = (EditText)findViewById(R.id.tiezi_fabiao_content);
		textView1 = (TextView)findViewById(R.id.tiezi_fabiao_fatie);
		textView2 = (TextView)findViewById(R.id.tiezi_content_dangqianzishu);
		textView3 = (TextView)findViewById(R.id.tiezi_content_zishu);
		imageView1 = (ImageView)findViewById(R.id.tiezi_fabiao_fanhui);
		
		linearLayout = (LinearLayout) findViewById(R.id.tiezi_fabiao_tupian);
		imageView2 = (ImageView) findViewById(R.id.tiezi_fabiao_tupian_tianjia);
		imageView1.setOnClickListener(this);
		imageView2.setOnClickListener(this);
		textView1.setOnClickListener(this);
	}

	private void initData() {
		textView2.setText("0");
		editText2.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				temp = arg0;
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				int number = s.length();
				textView2.setText("" + number);
				selectionStart = editText2.getSelectionStart();
				selectionEnd = editText2.getSelectionEnd();
				if (temp.length() > num) {
					s.delete(selectionStart - 1, selectionEnd);
					int tempSelection = selectionEnd;
					editText2.setText(s);
					editText2.setSelection(tempSelection);// 设置光标在最后
				}
			}
		});
		textView3.setText("/400");

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tiezi_fabiao_fanhui:
			Intent intent = new Intent(FatieActivity.this, MainActivity.class);
			startActivity(intent);
			break;
		case R.id.tiezi_fabiao_tupian_tianjia:
			index = -1;
			showPhotoDialog();
			break;
		case R.id.openCamera:
			System.out.println("点击打开相机");
			openCamera();
			break;
		case R.id.openPhones:
			openPhones();
			break;
		case R.id.cancel:
			dialog.cancel();
			break;
		case R.id.tiezi_fabiao_fatie:
				uploadGoods();
			Intent intent1 = new Intent(FatieActivity.this,
					MainActivity.class);
			startActivity(intent1);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case Config.REQUEST_CODE_CAMERA:
				File file = new File(this.getExternalCacheDir(), tempImgName);
				startPhotoZoom(Uri.fromFile(file));
				break;
			case Config.REQUEST_CODE_OPENPICS:
				Uri uri = data.getData();
				startPhotoZoom(uri);
				break;

			case Config.REQUEST_CODE_ZOOM:
				File file2 = new File(getExternalCacheDir(), tempImgName);
				addImageView(Uri.fromFile(file2));
				break;

			default:
				break;
			}
		}
	}

	void uploadGoods() {
		title = editText1.getText().toString();
		content = editText2.getText().toString();
		RequestParams params = new RequestParams();
		params.addBodyParameter("t_title", title);
		params.addBodyParameter("t_content", content);
		params.addBodyParameter("user_id", MyApplication.user_id);
		if (imgs_path != null) {
			for (int i = 0; i < imgs_path.size(); i++) {
				params.addBodyParameter("" + i, new File(imgs_path.get(i)));
			}
			params.addBodyParameter("key","1");
		}else {
			params.addBodyParameter("key","2");
		}
		HttpUtils httpUtils=new HttpUtils();
		String url = "http://" + MyApplication.getIP()
				+ ":8080/Jinnang/fatieJieshou";
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {
					@Override
					public void onFailure(HttpException arg0, String arg1) {		
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						
					}
				});
	}

	void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		tempImgName = StringUtils.getImageSaveName();
		intent.putExtra("output",
				Uri.fromFile(new File(this.getExternalCacheDir(), tempImgName)));
		startActivityForResult(intent, Config.REQUEST_CODE_ZOOM);
	}

	@SuppressWarnings("deprecation")
	void showPhotoDialog() {
		View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog11111,
				null);
		System.out.println("打开相机之前 调用弹出框");
		view.findViewById(R.id.openCamera).setOnClickListener(this);
		System.out.println("打开相机");
		view.findViewById(R.id.openPhones).setOnClickListener(this);
		System.out.println("打开图库");
		view.findViewById(R.id.cancel).setOnClickListener(this);
		System.out.println("调出三个选相框");
		dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
		dialog.setContentView(view, new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT));
		Window window = dialog.getWindow();
		// 设置显示动画
		window.setWindowAnimations(R.style.main_menu_animstyle);
		WindowManager.LayoutParams wl = window.getAttributes();
		wl.x = 0;
		wl.y = getWindowManager().getDefaultDisplay().getHeight();
		// 以下这两句是为了保证按钮可以水平满屏
		wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
		wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
		// 设置显示位置
		dialog.onWindowAttributesChanged(wl);
		// 设置点击外围解散
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
	}

	void openCamera() {
		System.out.println("进入相机");
		dialog.dismiss();
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		tempImgName = StringUtils.getImageSaveName();
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
				FatieActivity.this.getExternalCacheDir(), tempImgName)));

		startActivityForResult(intent, Config.REQUEST_CODE_CAMERA);
	}

	void openPhones() {
		System.out.println("打开图库");
		dialog.dismiss();
		Intent intent = new Intent(Intent.ACTION_PICK, null);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				"image/*");
		startActivityForResult(intent, Config.REQUEST_CODE_OPENPICS);
	}

	boolean checkGoodsParameter() {
		// 没有选择商品图片的
		if (editText2.getText().length() == 0) {
			editText2.requestFocus();
			return false;
		}
		return true;
	}

	void addImageView(Uri uri) {
		String img_path = getExternalCacheDir() + File.separator + tempImgName;
		if (index == -1) {
			final ImageView imageView = new ImageView(this);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					imageView2.getWidth(), imageView2.getHeight());
			params.setMargins(20, 0, 0, 0);
			imageView.setLayoutParams(params);
			imageView.setImageURI(uri);
			final int n = imgs_path.size();// 当前商品图片数量
			imageView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(final View v) {
					new AlertDialog.Builder(FatieActivity.this)
							.setNegativeButton(R.string.cancle,
									new DialogInterface.OnClickListener() {

										// 取消
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.cancel();
										}
									})
							.setNeutralButton(
									getResources().getString(R.string.edit),
									new DialogInterface.OnClickListener() {
										// 编辑
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											dialog.dismiss();
											showPhotoDialog();
											index = linearLayout
													.indexOfChild(v);

										}
									})
							.setPositiveButton(R.string.delete,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// 删除
											dialog.dismiss();
											removeImageView(v);
										}
									}).show();

				}
			});
			linearLayout.addView(imageView, n);
			// 添加图片路径
			imgs_path.add(img_path);

		} else {
			ImageView imageView = (ImageView) linearLayout.getChildAt(index);
			imageView.setImageURI(uri);
			imgs_path.set(index, img_path);
		}

	}

	void removeImageView(View v) {
		imgs_path.remove(linearLayout.indexOfChild(v));
		StringUtils.showToast(FatieActivity.this,
				"" + linearLayout.indexOfChild(v));
		linearLayout.removeView(v);
	}

}
